
import api from '../utils/api'
import {httpRequest,RSAencript} from "../utils/utils"
import {configOptions} from "../config"
let consultConfig,fromUser,toUser,srvInfo;
let checked = false; //用于检测权益标志
export default  {
    getChatPageUrl(options){
        const chatType = consultConfig && consultConfig.chatType == '2'?"GROUP":"C2C"
        const {account,toUser,isEnscript=false} = options
        let params = [
            `userID=${account.identifier}`,
            `userSig=${account.userSign}`,
            `userType=${account.userType}`,
            `signExpire=${account.signExpire}`,
            `destination=chat`,
            `chatType=${chatType}`,
            `idPi=${account.outUserId}`,
            `chatAccount=${toUser.identifier}`,
            `inspection=1`
        ]
        let paramString = Array.from(new Set(params)).join('&');
        let url = `${configOptions.options.url}/yj-consult-front/h5/#/`
        if(isEnscript){
            url+=`${this.getEnscriptChatPageUrl(paramString)}` 
        }else{
            url+=`?${paramString}`
        }
        if(!window){
            if(wx){
                wx.navigateTo({
                    url: `/yjConsult/pages/transfer/index?${paramString}`,
                })
            }else{
                console.error('出现异常，小程序环境下， wx.navigateTo跳转错误')
                return 
            }
        }else{
            if(window.wx && window.wx.miniProgram){
                wx.miniProgram.navigateTo({
                    url: `/yjConsult/pages/transfer/index?${paramString}`,
                })
            }else{
                console.log('咨询链接',url)
              //  window.location.href = url
            }
        }
        return url
    },
    getEnscriptChatPageUrl(paramString){
       return RSAencript(paramString)  
    },
    /**
     * @description 检查咨询
     */
    async startConsult(options){
        consultConfig = configOptions.options.consult;
        if(!consultConfig){
            if(!options){
                console.error(`{idPi,sysUserId,userType} is needed`) 
                return;
            }
            consultConfig = {
                idPi:options.idPi,
                sysUserId:options.sysUserId,
                userType: options.userType
            }
        }
        const {idPi,sysUserId,userType} = consultConfig
        const {success,fail} = options || {}
        try {
            if(!checked){
                srvInfo = await this.findLastedConsultSrvInfo({idPi,sysUserId})
                if(!srvInfo){
                  throw new Error('该会员无咨询服务权益')
                }
                checked = true
            }
            httpRequest(api.consult.checkConsult,{
                method:"post",
                body:{
                    idPi,
                    sysUserId,
                    userType
                }
            }).then((res)=>{
                const {code,msg,data} = res
                const {accounts} = data || {};
                fromUser = Array.isArray(accounts) && accounts.filter(item=>item.userType == consultConfig.userType)[0]
                toUser = Array.isArray(accounts) &&  accounts.filter(item=>item.userType != consultConfig.userType)[0]
              //  this.initSession({srvInfo,accounts})
                if(code == 200){
                    //提供回调，控制权交给用户
                    if(success && typeof success == 'function'){
                        success(data)
                    }else{
                        if(!data.hasRecord){
                           this.initSession({srvInfo,accounts})
                        }
                       //如果没有提供回调，默认按流程调用内部方法
                       this.getChatPageUrl({account:fromUser,toUser});
                    }
                }else{
                    if(fail && typeof fail == 'function'){
                        fail(msg)
                    }
                }
            })
        } catch (error) {
            if(fail && typeof fail == 'function'){
                fail(error)
            }
        }
        return this
    },
    /**
     * @description 服务结束后下次再重新初始化会话
     */
    initSession(options){
        const {success,fail,srvInfo} = options
        const {srvPiVo} = srvInfo;
        const params = {
            idPi: srvPiVo.idPi,
            idVissrvcardpi: srvPiVo.idVissrvcardpi,
            idVissrvcardpisrv: srvPiVo.idVissrvcardpisrv,
            cd: srvPiVo.cd,
            sysUserId: consultConfig.sysUserId,
            userType: consultConfig.userType,
            source: 1,
            fromAccount:fromUser.identifier,
            toAccount:toUser.identifier
        }
        try {
            httpRequest(api.consult.initSession,{
                method:"post",
                body:params
            }).then((res)=>{
                const {code,msg,data} = res
                if(code == 200){
                    if(success && typeof success == 'function'){
                        success(data)
                    }
                }else{
                    if(fail && typeof fail == 'function'){
                        fail(msg)
                    }
                }
            })
        } catch (error) {
            if(fail && typeof fail == 'function'){
                fail(error)
            }
        }
    },
    /**
     * @description 获取咨询服务最近快过期的卡和服务信息
     * @param {*} options 
     * @returns 
     */
    findLastedConsultSrvInfo(options){
       const {success,fail,idPi,sysUserId} = options 
    //    idPi = idPi || consultConfig.idPi
    //    sysUserId = sysUserId || consultConfig.sysUserId
       return new Promise((resolve,reject)=>{
            return httpRequest(`${api.consult.findConsultSrvInfo}?idPi=${idPi}&sysUserId=${sysUserId}`,{}).then((res)=>{
                const {code,msg,data} = res
                if(code == 200){
                    if(success && typeof success == 'function'){
                        success(data)
                    }else{
                        resolve(data)
                    }
                }else{
                    if(fail && typeof fail == 'function'){
                        fail(msg)
                    }else{
                        reject(new Error(msg))
                    }
                }
            }) 
       })
    },
    /**
     * @description 获取IM账号
     */
    getAccount(){
       return this
    },

}